package pf

import (
	. "chess_platform/internal/common"
	"chess_platform/models/partner"
	"chess_platform/modules"
	"fmt"
	"strings"
	"time"
)

//[h5]支付,对外接口，不需要token
type PayController struct {
	BaseController
}

func (b *PayController) URLMapping() {
	b.Mapping("IPayCallBack", b.IPayCallBack)
}

// @Title 爱贝支付回调接口(代理与玩家支付都可以回调此接口)
// @Description 爱贝支付回调接口(代理与玩家支付都可以回调此接口)
// @Success 0 {string} 状态码
// @router /ipay-callback [post]
func (b *PayController) IPayCallBack() {
	pay, err := H5IPay.ParseNotifyInfo(b.Ctx.Input.RequestBody)
	if err != nil {
		LogPF.Error(fmt.Sprintf("爱贝回调解析失败:%v\n回调参数(原始的):%v\n,回调参数(解析后):%#v\n",
			err, string(b.Ctx.Input.RequestBody), pay))
		return
	}
	LogPF.Debug(fmt.Sprintf("回调参数(原始的):%v\n,回调参数(解析后):%#v\n", string(b.Ctx.Input.RequestBody), pay))
	//rsp不会为nil
	//获取订单详情
	orderId := strings.Split(pay.CpOrderId, "-")[1]
	order, err := partner.OrderById(orderId)
	if err != nil {
		LogPF.Error(err.Error())
		return
	}
	//订单不存在
	if order == nil {
		return
	}

	//此订单已是成功发货的了，说明是微信重复通知，只需直接返回即可
	if order.Status == OrderDelivered {
		b.ResponseRawString("SUCCESS")
		return
	}

	if pay.Result == 1 { //交易失败,更新数据库订单为失败
		updateData := map[string]interface{}{
			"status":   OrderClosed,
			"pay_time": time.Now().Unix(),
		}
		_, err := partner.UpdateOrder(updateData, orderId)
		if err != nil {
			LogPF.Error(fmt.Sprintf("爱贝回调更新订单失败:%v", err.Error()))
			return
		}

	}
	//支付成功
	updateData := map[string]interface{}{
		"status":   OrderPaySuccess,
		"pay_time": time.Now().Unix(),
	}
	_, err = partner.UpdateOrder(updateData, orderId)
	if err != nil {
		LogPF.Error(err.Error())
		return
	}

	if order.OrderType == OrderDiamond {
		err = modules.DealPfAgentPay(order)
		if err != nil {
			LogPF.Error(err.Error())
			return
		}
	} else if order.OrderType == OrderAgentNum {
		//代理加上代理名额
		_, err = partner.UpdateUserAgentNum(order.CardNum, order.Uid)
		if err != nil {
			LogPF.Error(fmt.Sprintf("给代理(ID:%v)加上代理名额(%v)失败:%v", order.Uid, order.CardNum, err))
			return
		}
	}
	LogPF.Debug(fmt.Sprintf("爱贝回调:%v", pay))
	b.ResponseRawString("SUCCESS")
	return
}
